package com.chen.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

import com.chen.common.Result;
import com.chen.mapper.NewsMapper;
import com.chen.pojo.News;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("/new")
@SuppressWarnings("all")
public class NewsController {
    //依赖注入
    @Resource
    NewsMapper newsMapper;

    //    新增
    @PostMapping
    public Result<?> save(@RequestBody News news) {

        news.setTime(new Date());
        newsMapper.insert(news);
        return Result.success();

    }

    //更新
    @PutMapping
    public Result<?> update(@RequestBody News news) {
        newsMapper.updateById(news);
        return Result.success();
    }

    //删除
    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id) {
        newsMapper.deleteById(id);
        return Result.success();
    }

    //    查询
    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue = "1") Integer pageNum,  //页号
                              @RequestParam(defaultValue = "10") Integer pageSize, //一页展示的数量
                              @RequestParam(defaultValue = "") String search) {

//        模糊查询
        LambdaQueryWrapper<News> warapper = Wrappers.<News>lambdaQuery().like(News::getTitle, search);
        if (StrUtil.isBlank(search)) {
            warapper.like(News::getTitle, search);
        }
        Page<News> newsPage = newsMapper.selectPage(new Page<>(pageNum, pageSize), warapper);
        return Result.success(newsPage);

    }

}
